﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Modbus.Device;

namespace CrankShaftAnalysisSystem
{
    public partial class FormPanasonic : Form
    {
        public const ushort SpeedSetting1stSpeed = 0x3308;
        public const ushort CommandSpeed = 0x4024;
        public const ushort ActualSpeed = 0x4025;
        SerialPort serial = new SerialPort();
        ModbusSerialMaster master;
        Label[] labels;
        public bool[] ReadyState { set; get; } = new bool[3] { true, true, true };
        public FormPanasonic()
        {
            InitializeComponent();
            master = ModbusSerialMaster.CreateRtu(serial);
            labels = new Label[3] { lbVel1, lbVel2, lbVel3 };
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            serial.PortName = textBox1.Text;
            serial.BaudRate = 115200; //最大230400
            serial.ReadTimeout = 200;
            serial.Open();
            tmLoop.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            int vel = Convert.ToInt32(nmSpeed.Value);
            ushort[] registers = new ushort[2] { Tools.LowWord((uint)vel), Tools.HighWord((uint)vel)};
            master.WriteMultipleRegisters((byte)nmAxis.Value, SpeedSetting1stSpeed, registers);
            for (byte i = (byte)nmAxis.Minimum; i < nmAxis.Maximum + 1; i++)
            {
                try
                {
                    if(ReadyState[i-1])
                        labels[i - 1].Text = ((short)master.ReadHoldingRegisters(i, CommandSpeed, 1)[0]).ToString();
                }
                catch (Exception ex)
                {
                    ReadyState[i - 1] = false;
                    Console.WriteLine($"[Axis{i} Error]: {ex.Message}");
                }                
            }                
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            nmSpeed.Value = 0;
        }

        private void FormPanasonic_FormClosing(object sender, FormClosingEventArgs e)
        {
            Hide();
            e.Cancel = true;
        }
    }
}
